<template>
    <div>
      <el-form inline @submit.prevent="search" >
        <el-form-item>
          <el-input @keyup.enter="search" v-model="roleNames.roleName" placeholder="角色名称" />
        </el-form-item>
  
        <el-button :disabled = "roleNames.roleName !== '' ? false:true" type="primary" :icon="Search" @click="search">查询</el-button>
        <el-button @click="resetSearch">清空</el-button>
      </el-form>
  
      <div style="margin: 20px 0">
        <el-button type="primary" @click="addRole">添加</el-button>
      </div>
  
      <el-table border stripe style="width: 960px" v-loading="listLoading" :data="roles" @selection-change="handleSelectionChange">
  
        <el-table-column type="selection" width="55" />
  
        <el-table-column type="index" label="序号" width="80" align="center">
        </el-table-column>
  
        <el-table-column label="角色名称">
          <template v-slot="{row}">
            <template v-if="row.edit">
              <el-input @keyup.enter="updateRole(row)" v-model="row.role_name" class="edit-input" size="small" />
              <el-button class="cancel-btn" size="small" :icon="Refresh" type="warning" @click="cancelEdit(row)">
                取消
              </el-button>
              <el-button class="cancel-btn" size="small" :icon="Check" type="primary" @click="updateRole(row)">
                确认
              </el-button>
            </template>
            <span v-else>{{ row.role_name }}</span>
          </template>
        </el-table-column>
         
  
        <el-table-column label="操作" width="300" align="center">
          <template v-slot="{row}">
            <el-button size="small" :type="row.is_disable ==0?'warning':'danger'" :icon="Warning" :title="row.is_disable ==0?'点击禁用':'解除禁用'" @click="disables(row)" />
            <el-button size="small" :disabled="row.is_disable == 1" type="info" :icon="InfoFilled" title="分配权限" @click="$router.push(`/acl/role/auth?admin_role_id=${row.admin_role_id}&role_name=${row.role_name}`)" />
            <el-button size="small" :disabled="row.is_disable == 1" type="primary" :icon="Edit" title="修改角色" @click="row.edit= true" />
            <el-button size="small" type="danger" :icon="Delete" title="删除角色" @click="removeRole(row)" />
          </template>
        </el-table-column>
      </el-table>
  
      <!-- 分页组件 -->
      <el-pagination :current-page="page" :total="total" :page-size="limit" :page-sizes="[5, 10, 15, 20]" style="padding: 20px 0;" layout="prev, pager, next, jumper, ->, sizes, total" @current-change="getRoles" @size-change="getRoles(1, $event)" />
    </div>
  </template>
  
  <script lang="ts">
  export default {
    name: 'Role'
  }
  </script>
  
  <script lang="ts" setup>
  import { ref, reactive, onMounted } from 'vue'
  import {
    ElForm,
    ElFormItem,
    ElInput,
    ElButton,
    ElTable,
    ElTableColumn,
    ElPagination,
    ElMessage,
    ElMessageBox
  } from 'element-plus'
  import {
    Search,
    Edit,
    Delete,
    Refresh,
    InfoFilled,
    Check,
    Warning
  } from '@element-plus/icons-vue'
  import {
    updateRoleApi,
    removeRoleApi,
    getRoleListApi,
    saveRoleApi,
    reqGetDisabled,
getUserInfoApi,
  } from '@/api/acl/role'
  
  const listLoading = ref(false) // 数据是否正在加载
  const roles = ref<any>([]) // 角色列表
  const total = ref(0) // 总记录数
  const page = ref(1) // 当前页码
  const limit = ref(5) // 每页记录数
  const roleNames = reactive({
    // 用户搜索的用户名
    roleName: '',
    searchRoleName: ''
  })
  const selectedRoles = ref<any>([]) // 所有选中的角色列表
  const menuids = ref<any>([])
  onMounted(() => {
    getRoles()
  })
  
  /* 
    取消修改
    */
  const cancelEdit = (role: any) => {
    role.roleName = role.originRoleName as string
    role.edit = false
    ElMessage.warning('取消角色修改')
  }
  
  /* 
    更新角色
    */
  const updateRole = async(role: any) => {
    const info = await getUserInfoApi(role.admin_role_id)
    const result = await updateRoleApi(role.admin_role_id,role.role_name,info.admin_menu_ids)
    ElMessage.success('更新角色成功!')
      getRoles()
  }
  
  /* 
    添加角色
    */
  const addRole = () => {
    // 显示添加界面
    ElMessageBox.prompt('请输入新名称', '添加角色', {
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    })
      .then(({ value }) => {
        saveRoleApi({ role_name: value }).then(() => {
          ElMessage.success('添加角色成功')
          getRoles()
        })
      })
      .catch(() => {
        ElMessage.warning('取消添加')
      })
  }
  
  /* 
    异步获取角色分页列表
    */
  const getRoles = (p = page.value, size = limit.value) => {
    page.value = p
    limit.value = size
    listLoading.value = true
    getRoleListApi(p, size, roleNames.searchRoleName)
      .then((result) => {
        roles.value = result.list.map((item:any) => {
          item.edit = false // 用于标识是否显示编辑输入框的属性
          item.originRoleName = item.role_name // 缓存角色名称, 用于取消
          return item
        })
        total.value = result.count
      })
      .finally(() => {
        listLoading.value = false
      })
  }
  
  /* 
    根据搜索条件进行搜索
    */
  const search = () => {
    roleNames.searchRoleName = roleNames.roleName
    getRoles()
  }
  
  /* 
    重置查询表单搜索列表
    */
  const resetSearch = () => {
    roleNames.roleName = ''
    roleNames.searchRoleName = ''
    getRoles()
  }
  
  /* 
    删除指定的角色
    */
  const removeRole = (role: any) => {
    ElMessageBox.confirm(`确定删除 '${role.role_name}' 吗?`, '提示', {
      type: 'warning'
    })
      .then(async () => {
        await removeRoleApi(role.admin_role_id as string)
        getRoles(roles.value.length === 1 ? page.value - 1 : page.value)
        ElMessage.success('删除成功!')
      })
      .catch(() => {
        ElMessage.info('已取消删除')
      })
  }
  
  /* 
    当表格复选框选项发生变化的时候触发
    */
  const handleSelectionChange = (selection: any) => {
    selectedRoles.value = selection
  }
  
  const disables = (row:any)=>{
    const is_disable = row.is_disable ===0?1:0
    reqGetDisabled(row.admin_role_id,is_disable).then((res)=>{
      ElMessage.success('修改成功!')
      getRoles()
    })
  }
  </script>
  <style scoped lang="scss">
    .el-form-item {
      margin-bottom: 0;
    }
  </style>
  